﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using CharitiesLib;
using System.Windows.Forms;
using Charities.ModelViews;

namespace Charities
{
    public partial class GrantEditor : Form
    {
        int worthyId = -1;
        int userid = -1;
        string issunumber = "";
        public bool is_loaded;
        List<Worthy> worthies = new List<Worthy>();
        List<Grant> ShedGrants = new List<Grant>();
        List<GrantView> grViewList = new List<GrantView>();
        Form fo = null;
        public GrantEditor(int uid, int id,Form m)
        {
            fo = m;
            this.MdiParent = m;
            InitializeComponent();
            userid = uid;
            worthyId = id;
            
        }
        public GrantEditor(int uid, List<Worthy> wor,Form m)
        {
            fo = m;
            this.MdiParent = m;
            userid = uid;
            worthies = wor;

            InitializeComponent();
        }
        public GrantEditor(int uid, List<Worthy> wor, Form m,List<Grant> Shedualed)
        {
            fo = m;
            this.MdiParent = m;
            userid = uid;
            worthies = wor;
            ShedGrants = Shedualed;
            InitializeComponent();
            
        }
        public GrantEditor(int uid, int id, string Issunumber,Form m)
        {
            fo = m;
            this.MdiParent = m;
            InitializeComponent();
            worthyId = id;
            userid = uid;
            issunumber = Issunumber;
            txb_IssueNumber.Text = Issunumber.ToString();
        }
        ModelContainer ctx = new ModelContainer();
        Grant grant = new Grant();

        private void GrantEditor_Load(object sender, EventArgs e)
        {
            User user = ctx.Users.Single(u => u.Id == userid);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name)
                {
                    case "GRANTS_DELIVER":
                        btn_EnterDetails.Visible = true;
                        break;
                    case "GRANTS_IMPORT":
                        btn_Import.Visible = true;
                        break;
                    default:
                        break;
                }
            }
            if (issunumber.Length > 0 && worthyId <= 0)
            {
                btn_EnterDetails.Text = "  تسليم  المنحة";
                List<Grant> grants = ctx.Grants.Where(g => g.IssueNumber == txb_IssueNumber.Text).ToList();
                txb_IssueNumber.Enabled = false;
                foreach (var grant in grants)
                {
                    GrantView grv = new GrantView();
                    grv=ShowGrantAsGrantsView(grant);
                    grViewList.Add(grv);
                }
                lstbox_grants.DataSource = grViewList;
                lstbox_grants.DisplayMember = "name";
                lstbox_grants.ValueMember = "Id";
            }
            else if (issunumber.Length > 0 && worthyId > 0)
            {
                btn_EnterDetails.Text = "  تسليم  المنحة";
                is_loaded = true;
                Worthy wor = ctx.Worthies.Single(wo => wo.Id == worthyId);
                Person person = ctx.People.Single(p => p.Id == wor.PersonId);
                txb_worthyName.Text = string.Format("{0} {1} {2}", person.FirstName, person.FatherName, person.LastName);
                txb_worthyId.Text = worthyId.ToString();
                txb_IssueNumber.Enabled = false;

                foreach (var grant in wor.Grants.Where(c=>c.IssueNumber==issunumber))
                {
                    GrantView grv = new GrantView();
                    grv = ShowGrantAsGrantsView(grant);
                    grViewList.Add(grv);
                }
            }

            else if (issunumber.Length <= 0 && worthies.Count() == 0)
            {
                is_loaded = true;
                txb_worthyName.Text = (from p in ctx.People where p.WorthyId == worthyId select (p.FirstName + " " + p.FatherName + " " + p.LastName)).First();
                txb_worthyId.Text = worthyId.ToString();
            }
            else if (issunumber.Length <= 0 && worthies.Count() > 0)
            {
                txb_worthyName.Text = "مجموعة البحث";
                txb_worthyId.Text = "مجموعة البحث";
            }
            else if (worthies.Count() == 0 || worthyId > 0)
            {
                is_loaded = true;
                Worthy wor = ctx.Worthies.Single(wo => wo.Id == worthyId);
                Person person = ctx.People.Single(p => p.Id == wor.PersonId);
                txb_worthyName.Text = string.Format("{0} {1} {2}", person.FirstName, person.FatherName, person.LastName);
                txb_worthyId.Text = worthyId.ToString();
                txb_IssueNumber.Enabled = false;
            }
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);

            lstbox_grants.DataSource = null;
            lstbox_grants.DataSource = grViewList;
            lstbox_grants.DisplayMember = "name";
            lstbox_grants.ValueMember = "Id";

        }
        string errorSatatus = string.Empty;

        //Add Add grants To ListBox_Grants
        private GrantView ShowGrantAsGrantsView(Grant grant)
        {
            GrantView grantView = new GrantView();
            foreach (var gditem in grant.GrantDetails.ToList())
            {
                if (grant.CartId != null && gditem.SupplyId == null)
                {
                   
                    if (grant.Schedules.Count() > 0)
                    {
                        grantView.name = " (مجدولة) " + grant.Cart.Name + " ~عدد: " + gditem.Amount;
                        grantView.Id = grant.Id;
                    }
                    else
                    {
                        if (gditem.Grant.IsDelivered == true)
                        {
                            grantView.name = " (مسلّمة) " + grant.Cart.Name + " ~عدد: " + gditem.Amount;
                            grantView.Id = grant.Id;
                        }
                        else
                        {
                            grantView.name = " (غير مسلّمة) " + grant.Cart.Name + " ~عدد: " + gditem.Amount;
                            grantView.Id = grant.Id;
                        }
                    }
                    if (grant.IsDelivered == true)
                    {
                        chkbox_IsDelivered.Checked = true;
                        chkbox_IsDelivered.Enabled = false;
                        btn_EnterDetails.Enabled = false;
                    }
                    else
                    {
                        chkbox_IsDelivered.Checked = false;
                        btn_EnterDetails.Enabled = true;
                    }
                 
                }
                else if (grant.CartId == null && gditem.SupplyId != null)
                {
                   
                    if (grant.Schedules.Count() > 0)
                    {
                        grantView.name = " (مجدولة) " + gditem.Supply.Name + " ~عدد: " + gditem.Amount;
                        grantView.Id = grant.Id;
                    }
                    else
                    {
                        if (gditem.Grant.IsDelivered == true)
                        {
                            grantView.name = " (مسلّمة) " + gditem.Supply.Name + " ~عدد: " + gditem.Amount;
                            grantView.Id = grant.Id;
                        }
                        else
                        {
                            grantView.name = " (غير مسلّمة) " + gditem.Supply.Name + " ~عدد: " + gditem.Amount;
                            grantView.Id = grant.Id;
                        }
                    }
                    if (grant.IsDelivered == true)
                    {
                        chkbox_IsDelivered.Checked = true;
                        chkbox_IsDelivered.Enabled = false;
                        btn_EnterDetails.Enabled = false;
                    }
                    else
                    {
                        chkbox_IsDelivered.Checked = false;
                        btn_EnterDetails.Enabled = true;
                    }
                }
            }
            return grantView;
        }

        private void btn_Import_Click(object sender, EventArgs e)
        {
            if (worthies.Count() > 0)
            {
                txb_worthyName.Text = "مجموعة البحث";
                txb_worthyId.Text = "مجموعة البحث";
                foreach (var worthy in worthies)
                {
                    Grant g = new Grant();
                    g= GrantOps(worthy.Id);
                    g.IsDelivered = chkbox_IsDelivered.Checked;
                    if (rb_Carts.Checked)
                    {
                        g.CartId = (int)cbo_suply_Carts.SelectedValue;
                    }
                    if (chkbox_schedualedGrant.Checked)
                    {
                        NextGrant(g);
                    }
                    ctx.Grants.Add(g);
                }
            }
            else
            {
                Grant g = new Grant();
                g= GrantOps(worthyId);
                g.IsDelivered = chkbox_IsDelivered.Checked;
                if (chkbox_schedualedGrant.Checked)
                {
                    NextGrant(g);
                }
                ctx.Grants.Add(g);
            }
            txb_Ammount.Clear();
            ctx.SaveChanges();
            lstbox_grants.DataSource = null;
            lstbox_grants.DataSource = grViewList;
            lstbox_grants.DisplayMember = "name";
            lstbox_grants.ValueMember = "Id";
        }
        private void GrantShedOps(Grant sGrant, Schedule shed)
        {
            if (sGrant != null && shed != null)
            {
                Grant sGrant1 = new Grant();
                if (txb_Ammount.Text.Length > 0)
                {
                    sGrant1.IssueDate = dtp_issuerDate.Value;
                    sGrant1.IssueNumber = txb_IssueNumber.Text;
                }
                else
                {
                    errorSatatus += "رقم وتاريخ المنحة مطلوبان" + "\n";
                }
                if (rb_Carts.Checked)
                {
                    sGrant1.GrantDetails.Add(AddCardDetail());
                    sGrant1.CartId = (int)cbo_suply_Carts.SelectedValue;
                }
                else if (rb_supply.Checked)
                {
                    sGrant1.GrantDetails.Add(AddSupplyDetail());
                }
                sGrant1.IssueDate = sGrant.IssueDate;
                sGrant1.IssueNumber = sGrant.IssueNumber;
                sGrant1.IsDelivered = false;
                sGrant1.InsertDate = DateTime.Now;
                sGrant1.InsertUId = userid;
                sGrant1.WorthyId = sGrant.WorthyId;
                sGrant1.CartId = sGrant.CartId;
                sGrant1.DateOfDelivery = sGrant.DateOfDelivery;
                sGrant1.DueToDate = sGrant.DueToDate;

                try
                {
                    if (sGrant1.Schedules.Count() > 0)
                    {
                        GrantView grview = new GrantView();
                        grview.name = "مجدولة:"+cbo_suply_Carts.Text + '~' + " \tعدد: " + txb_Ammount.Text;
                        grview.Id = sGrant1.Id;
                        grViewList.Add(grview);
                       
                    }
                    else
                    {
                        GrantView grview = new GrantView();
                        grview.name = cbo_suply_Carts.Text + '~' + " \tعدد: " + txb_Ammount.Text;
                        grview.Id = sGrant1.Id;
                        grViewList.Add(grview);
                     
                    }
                    sGrant1.Schedules.Add(shed);
                    ctx.Grants.Add(sGrant1);

                }
                catch (Exception)
                {
                    MessageBox.Show(errorSatatus, "حصلت الأخطاء التالية يرجى التحقق ", MessageBoxButtons.OK);
                }
            }
        }
        
        private GrantDetail AddCardDetail()
        {
            if (rb_Carts.Checked)
            {
                int cid = (int)cbo_suply_Carts.SelectedValue;
                Cart c = ctx.Carts.Single(s => s.Id == cid);
                GrantDetail gd = new GrantDetail();
                GrantView gv = new GrantView();
                double ammou;
                if (Double.TryParse(txb_Ammount.Text, out ammou))
                {
                    gd.Amount = ammou;
                }
                else
                {
                    errorSatatus += "الكمية يجب أن تكون رقم صحيح أو عشري" + "\n";
                }
                gd.InsertDate = DateTime.Now;
                gd.InsertUId = userid;
                if (chkbox_IsDelivered.Checked)
                {
                    List<CartDetail> cdls = ctx.CartDetails.Where(d => d.CartId == c.Id).ToList();
                    foreach (var item in cdls)
                    {
                        Supply supl = ctx.Supplies.Single(cu => cu.Id == item.SupplyId);
                        supl.Amount = supl.Amount - (ammou * item.Amount);

                    }
                    gv.name=" ( مسلّمة ) "+cbo_suply_Carts.Text+" عدد: "+txb_Ammount.Text;
                    gv.Id = gd.GrantId;
                }
                else
                {
                    gv.name = " (  غير مسلّمة ) " + cbo_suply_Carts.Text + " عدد: " + txb_Ammount.Text;
                    gv.Id = gd.GrantId;
                }
                grViewList.Add(gv);

                return gd;
            }
            else
            {
                return null;
            }

        }
        
        private GrantDetail AddSupplyDetail()
        {
            if (rb_supply.Checked)
            {
                GrantDetail gd = new GrantDetail();
                GrantView gv = new GrantView();
                Supply sup = ctx.Supplies.Single(s => s.Name == cbo_suply_Carts.Text);
                gd.SupplyId = sup.Id;
                double ammou;
                if (Double.TryParse(txb_Ammount.Text, out ammou))
                {
                    gd.Amount = ammou;
                }
                else
                {
                    errorSatatus += "الكمية يجب أن تكون رقم صحيح أو عشري" + "\n";
                }
                gd.InsertDate = DateTime.Now;
                gd.InsertUId = userid;
                if (chkbox_IsDelivered.Checked)
                {
                    sup.Amount = sup.Amount - ammou;
                    gv.name = " ( مسلّمة ) " + cbo_suply_Carts.Text + " عدد: " + txb_Ammount.Text;
                    gv.Id = gd.GrantId;
                }
                else
                {
                    gv.name = " (  غير مسلّمة ) " + cbo_suply_Carts.Text + " عدد: " + txb_Ammount.Text;
                    gv.Id = gd.GrantId;
                }
                grViewList.Add(gv);
                return gd;
                
            }
            else
            {
                return null;
            }
        }

        private Grant GrantOps(int wid)
        {
            if (wid > 0)
            {
                string errorSatatus = string.Empty;

                try
                {
                    Worthy worthy = null;
                    try
                    {
                        worthy = ctx.Worthies.Single(c => c.Id == wid && c.IsActive == true);
                    }
                    catch (Exception)
                    {
                        errorSatatus += "المستخدم غير موجود أو مرقن قيده" + "\n";
                    }
                    Grant g = new Grant();
                    g.WorthyId = worthy.Id;
                    g.InsertDate = DateTime.Now;
                    g.DateOfDelivery = dtp_WorthyDate.Value;
                    if (txb_Ammount.Text.Length > 0)
                    {
                        g.IssueDate = dtp_issuerDate.Value;
                        g.IssueNumber = txb_IssueNumber.Text;
                    }
                    else
                    {
                        errorSatatus += "رقم وتاريخ المنحة مطلوبان" + "\n";
                    }
                    g.InsertUId = userid;

                    if (rb_Carts.Checked)
                    {
                        g.GrantDetails.Add(AddCardDetail());
                        g.CartId = (int)cbo_suply_Carts.SelectedValue;
                    }
                    else if (rb_supply.Checked)
                    {
                        g.GrantDetails.Add(AddSupplyDetail());
                    }
                    return g;
                }
                catch (Exception)
                {
                    MessageBox.Show(errorSatatus, "حصلت الأخطاء التالية يرجى التحقق من ", MessageBoxButtons.OK);
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        private void NextGrant(Grant grant)
        {
            
            int schedual = cbo_ShedualType.SelectedIndex;
            DateTime endDate = dtp_endDate.Value;
            switch (schedual)
            {
                case 0:
                    foreach (var day in EachDay(dtp_issuerDate.Value.AddDays(1), dtp_endDate.Value))
                    {
                        Schedule sh = new Schedule();
                        sh.ScheduleType = cbo_ShedualType.SelectedText;
                        sh.InsertDate = DateTime.Now;
                        sh.InsertUId = userid;
                        sh.NextGrantDate = day;
                        sh.ScheduleType = cbo_ShedualType.Text;
                        grant.IsDelivered = chkbox_IsDelivered.Checked;
                        grant.DateOfDelivery = day;
                        grant.DueToDate = day;
                        GrantShedOps(grant,sh);
                    }
                    break;
                case 1:
                    for (var i = DateTime.Now.Date.AddDays(7); i <= endDate.Date; i=i.AddDays(7))
                    {
                        Schedule sh = new Schedule();
                        sh.ScheduleType = cbo_ShedualType.SelectedText;
                        sh.InsertDate = DateTime.Now;
                        sh.InsertUId = userid;
                        sh.NextGrantDate = i;
                        sh.ScheduleType = cbo_ShedualType.Text;
                        grant.Schedules.Add(sh);
                        grant.IsDelivered = false;
                        grant.DateOfDelivery = i;
                        grant.DueToDate = i;
                        GrantShedOps( grant,sh);
                    }

                    break;
                case 2:
                    for (var i = DateTime.Now.Date.AddMonths(1); i <= endDate.Date; i=i.AddMonths(1))
                    {
                        Schedule sh = new Schedule();
                        sh.ScheduleType = cbo_ShedualType.SelectedText;
                        sh.GrantId = grant.Id;
                        sh.InsertDate = DateTime.Now;
                        sh.InsertUId = userid;
                        sh.NextGrantDate = i;
                        sh.ScheduleType = cbo_ShedualType.Text;
                        grant.IsDelivered = false;
                        grant.DateOfDelivery = i;
                        grant.DueToDate = i;
                        GrantShedOps(grant,sh);
                    }

                    break;
                case 3:
                    for (var i = DateTime.Now.Date.AddYears(1); i <= endDate.Date; i=i.AddYears(1))
                    {
                        Schedule sh = new Schedule();
                        sh.ScheduleType = cbo_ShedualType.SelectedText;
                        sh.GrantId = grant.Id;
                        sh.InsertDate = DateTime.Now;
                        sh.InsertUId = userid;
                        sh.NextGrantDate = i;
                        sh.ScheduleType = cbo_ShedualType.Text;
                        grant.IsDelivered = false;
                        grant.DateOfDelivery = i;
                        grant.DueToDate = i;
                        GrantShedOps(grant,sh);
                    }

                    break;
                default:
                    break;
            }

            ctx.SaveChanges();
            
        }

        private void rb_Carts_CheckedChanged(object sender, EventArgs e)
        {
            if (rb_Carts.Checked)
            {
                List<Cart> carts = (from c in ctx.Carts select c).ToList();
                cbo_suply_Carts.DisplayMember = "Name";
                cbo_suply_Carts.ValueMember = "Id";
                cbo_suply_Carts.DataSource = carts;

            }
            else if (rb_supply.Checked)
            {
                List<Supply> supplies = (from s in ctx.Supplies select s).ToList();
                cbo_suply_Carts.DataSource = supplies;
                cbo_suply_Carts.DisplayMember = "Name";
                cbo_suply_Carts.ValueMember = "Id";
            }
        }

        private void btn_EnterDetails_Click(object sender, EventArgs e)
        {
            if (btn_EnterDetails.Text == "إدخال تفاصيل المنحة")
            {
                if (issunumber.Length > 0 && chkbox_IsDelivered.Checked)
                {
                    List<Grant> grnats = ctx.Grants.Where(g => g.IssueNumber == txb_IssueNumber.Text && g.WorthyId==worthyId).ToList();
                    foreach (var grant in grnats)
                    {
                        grant.DeliverGrant(userid);
                    }
                    ctx.SaveChanges();
                    btn_EnterDetails.Enabled = false;
                }
                else
                {
                    rb_Carts.Enabled = true;
                    rb_supply.Enabled = true;
                    cbo_suply_Carts.Enabled = true;
                    txb_Ammount.Enabled = true;
                    lstbox_grants.Enabled = true;
                }
            }
            else if (btn_EnterDetails.Text == "  تسليم  المنحة")
            {
                List<Grant> grants = ctx.Grants.Where(c => c.IssueNumber == issunumber && c.WorthyId == worthyId).ToList();
                DialogResult res = MessageBox.Show(" هل تريد تأكيد تسليم المنحة رقم: " + issunumber + "بكامل عناصرها؟", "تأكيد التسليم؟", MessageBoxButtons.YesNo);
                if (res == DialogResult.Yes)
                {
                    List<Grant> grnats = ctx.Grants.Where(g => g.IssueNumber == txb_IssueNumber.Text && g.WorthyId == worthyId).ToList();
                    foreach (var grant in grnats)
                    {
                        grant.DeliverGrant(userid);
                        if (grant.Schedules.Count() > 0)
                        {
                            if (grant.Schedules.Count() > 0)
                            {
                                foreach (var item in grant.Schedules.ToList())
                                {
                                    grant.Schedules.Remove(item);
                                }
                            }
                        }
                    }
                    MessageBox.Show("تم وضع علامة مسلمة على المنح ", "تأكيد تسليم كافة المنح", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                ctx.SaveChanges();
                btn_EnterDetails.Enabled = false;

            }
            else if (btn_EnterDetails.Text == "  تسليم  المنحة المحددة")
            {
                if (lstbox_grants.SelectedValue != null)
                {
                    int gId = (int)lstbox_grants.SelectedValue;
                    if (gId > 0)
                    {
                        DialogResult res = MessageBox.Show("هل تريد تأكيد تسليم المنحة"+lstbox_grants.Text, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (res == DialogResult.Yes)
                        {
                            Grant grant = ctx.Grants.Single(g => g.Id == gId);
                            grant.DeliverGrant(userid);
                            if (grant.Schedules.Count() > 0)
                            {
                                foreach (var item in grant.Schedules.ToList())
                                {
                                    ctx.Database.ExecuteSqlCommand("Delete from dbo.Schedules Where GrantId=" + item.GrantId);
                                }
                            }
                            ctx.SaveChanges();
                            MessageBox.Show("  تم وضع علامة مسلمة على المنحة"+lstbox_grants.Text, "تأكيد تسليم منحة وحيدة", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            if (grViewList.Count() > 0)
                            {
                                grViewList.Single(g => g.Id == grant.Id).name = grViewList.Single(g => g.Id == grant.Id).name.Replace("غير مسلّمة", "مسلّمة");
                                grViewList.Single(g => g.Id == grant.Id).name = grViewList.Single(g => g.Id == grant.Id).name.Replace("مجدولة", "مسلّمة");
                                
                            }
                        }
                    }
                }
            }
            lstbox_grants.DataSource = null;
            lstbox_grants.DataSource = grViewList;
            lstbox_grants.DisplayMember = "name";
            lstbox_grants.ValueMember = "Id";
        }

        private void txb_Ammount_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !Char.IsNumber(e.KeyChar) && e.KeyChar != 8 && e.KeyChar!='.';

        }
        private void txb_Ammount_TextChanged(object sender, EventArgs e)
        {
            if (txb_Ammount.Text.Length > 0)
            {
                btn_Import.Enabled = true;
            }
            else
            {
                btn_Import.Enabled = false;
            }
        }
        public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
        {
            for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
                yield return day;
        }
        public IEnumerable<DateTime> EachWeek(DateTime from, DateTime thru)
        {
            for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(7))
                yield return day;
        }
        public IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
        {
            for (var month = from.Date; month.Date <= thru.Date; month = month.AddMonths(1))
                yield return month;
        }
        public IEnumerable<DateTime> EachYear(DateTime from, DateTime thru)
        {
            for (var year = from.Date; year.Date <= thru.Date; year = year.AddDays(1))
                yield return year;
        }

        private void chkbox_schedualedGrant_CheckedChanged(object sender, EventArgs e)
        {
            if (chkbox_schedualedGrant.Checked)
            {
                dtp_endDate.Enabled = true;
                cbo_ShedualType.Enabled = true;
            }
            else
            {
                dtp_endDate.Enabled = false;
                cbo_ShedualType.Enabled = false;
            }
        }

        private void GrantEditor_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void GrantEditor_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void txb_IssueNumber_TextChanged(object sender, EventArgs e)
        {
            if (txb_IssueNumber.Text.Length == 0)
            {
                btn_EnterDetails.Enabled = false;
            }
            else
            {
                btn_EnterDetails.Enabled = true;
            }

        }

        private void lstbox_grants_SelectedIndexChanged(object sender, EventArgs e)
        { 
            lstbox_grants.DisplayMember = "name";
                lstbox_grants.ValueMember = "Id";
            if (lstbox_grants.SelectedValue != null)
            {
                lstbox_grants.DisplayMember = "name";
                lstbox_grants.ValueMember = "Id";
                int grantId = (int)lstbox_grants.SelectedValue;
                if (grantId > 0)
                {
                    Grant grnt = ctx.Grants.Single(g => g.Id == grantId);
                    if (grnt.IsDelivered!=true)
                    {
                        btn_EnterDetails.Text = "  تسليم  المنحة المحددة";
                        btn_EnterDetails.Enabled = true;
                        btnDelete.Visible = true;
                        if (grnt.Schedules.Any())
                        {
                            dtp_WorthyDate.Value = grnt.Schedules.First().NextGrantDate.Date;
                        }
                    }
                    else
                    {
                        btn_EnterDetails.Text = "إدخال تفاصيل المنحة";
                        btn_EnterDetails.Enabled = false;
                        btnDelete.Visible = false;
                       
                    }
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstbox_grants.SelectedValue != null)
            {
                lstbox_grants.DisplayMember = "name";
                lstbox_grants.ValueMember = "Id";
                int grantId = (int)lstbox_grants.SelectedValue;
                if (grantId > 0)
                {
                    Grant grnt = ctx.Grants.Single(g => g.Id == grantId);
                    if (grnt.IsDelivered != true)
                    {
                        DialogResult res = MessageBox.Show("هل تريد بالتأكيد حذف تفصيل المنحة: "+lstbox_grants.Text,"تأكيد حذف تفصيل منحة",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                        if (res == DialogResult.Yes)
                        {
                            var grantV = grViewList.Where(g => g.Id == grantId).First();
                                grViewList.Remove(grantV);
                                ctx.Database.ExecuteSqlCommand("DELETE From dbo.Schedules WHERE GrantId=" + grantId);
                                ctx.Database.ExecuteSqlCommand("DELETE From dbo.Grants WHERE Id=" + grantId);
                                ctx.SaveChanges();
                               
                                lstbox_grants.DataSource = null;
                                lstbox_grants.DataSource = grViewList;
                                lstbox_grants.DisplayMember = "name";
                                lstbox_grants.ValueMember = "Id";
                        }
                    }
                    else
                    {
                        MessageBox.Show("لايمكن حذف منحة مسلمة ","لم يتم الحذف",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
